package com.ff.xyh.access.controller.access;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ff.xyh.access.service.access.*;
import com.ff.xyh.common.entity.result.ResultMessage;
import com.ff.xyh.common.entity.result.ResultObject;
import com.ff.xyh.common.entity.useraccess.AccessRolePermission;
import com.ff.xyh.common.entity.useraccess.AccessUserRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 后台许可表 前端控制器
 * </p>
 *
 * @author ff
 * @since 2022-10-30
 */
@Api(tags = "后台用户角色权限信息接口")
@RestController
@RequestMapping("/access")
public class AccessUserAndRoleAndPermissionController {

    @Autowired
    private AccessPermissionService accessPermissionService;
    @Autowired
    private AccessRolePermissionService accessRolePermissionService;
    @Autowired
    private AccessRoleService accessRoleService;
    @Autowired
    private AccessUserRoleService accessUserRoleService;
    @Autowired
    private AccessUserService accessUserService;

    /** role-permission */

//    @ApiOperation(value = "查询所有角色权限")
//    @GetMapping("rolePermission/get/all")
//    public ResultObject getAllAccessRolePermission() {
//        List<AccessRolePermission> list = accessRolePermissionService.list(null);
//        if (list == null || list.isEmpty()){
//            return ResultObject.error().message(ResultMessage.NO_RESULT);
//        } else {
//            return ResultObject.ok().data("items", list);
//        }
//    }

    @ApiOperation(value = "根据roleId查询角色权限列表")
    @GetMapping("rolePermission/get/list/role/{roleId}")
    public ResultObject getAccessRolePermissionListByRoleId(
            @PathVariable String roleId) {
        QueryWrapper<AccessRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        List<AccessRolePermission> list = accessRolePermissionService.list(wrapper);
        if (list == null || list.isEmpty()){
            return ResultObject.error().message(ResultMessage.NO_RESULT);
        } else {
            return ResultObject.ok().data("items", list);
        }
    }

    @ApiOperation(value = "根据permissionId查询角色权限列表")
    @GetMapping("rolePermission/get/list/permission/{permissionId}")
    public ResultObject getAccessRolePermissionByPermissionId(
            @PathVariable String permissionId) {
        QueryWrapper<AccessRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("permission_id", permissionId);
        List<AccessRolePermission> list = accessRolePermissionService.list(wrapper);
        if (list == null || list.isEmpty()){
            return ResultObject.error().message(ResultMessage.NO_RESULT);
        } else {
            return ResultObject.ok().data("items", list);
        }
    }

    @ApiOperation(value = "删除角色权限")
    @PostMapping("rolePermission/delete")
    public ResultObject deleteAccessRolePermission(
            @RequestBody AccessRolePermission accessRolePermission) {
        QueryWrapper<AccessRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", accessRolePermission.getRoleId())
                .eq("permission_id", accessRolePermission.getPermissionId());
        if (accessRolePermissionService.getOne(wrapper) == null){
            return ResultObject.error().message(ResultMessage.NO_SUCH_OBJECT);
        } else {
            if (accessRolePermissionService.remove(wrapper)) {
                return ResultObject.ok().data("data", accessRolePermission);
            } else {
                return ResultObject.error().message(ResultMessage.OBJECT_EXISTS_BUT_FAILED_TO_DELETE);
            }
        }
    }

    @ApiOperation(value = "添加角色权限")
    @PostMapping("rolePermission/add")
    public ResultObject addAccessRolePermission (
            @RequestBody AccessRolePermission accessRolePermission) {
        QueryWrapper<AccessRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", accessRolePermission.getRoleId()).eq("permission_id", accessRolePermission.getPermissionId());
        if (accessRolePermissionService.getOne(wrapper) != null){
            return ResultObject.error().message(ResultMessage.OBJECT_ALREADY_EXISTS);
        } else {
            if (accessRolePermissionService.save(accessRolePermission)) {
                return ResultObject.ok().data("data", accessRolePermission);
            } else {
                return ResultObject.error().message(ResultMessage.NO_SUCH_OBJECT_BUT_FAILED_TO_INSERT);
            }
        }
    }

    @ApiOperation(value = "为角色设置权限")
    @PostMapping("rolePermission/set")
    public ResultObject setPermissionsToRole(
            @RequestParam String roleId, @RequestParam String[] permissionIds) {
        QueryWrapper<AccessRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);

        if (!accessRolePermissionService.remove(wrapper)) { // 删除失败 可能是没有记录
            if (accessRolePermissionService.getOne(wrapper) != null) { // 存在记录
                return ResultObject.error().message("设置失败");
            }
        }
        List<AccessRolePermission> saveList = new ArrayList<>();
        for (String permissionId : permissionIds) {
            if (!StringUtils.isEmpty(permissionId)) {
                saveList.add(new AccessRolePermission().setRoleId(roleId).setPermissionId(permissionId));
            }
        }
        accessRolePermissionService.saveBatch(saveList);
        return ResultObject.ok();
    }


    /** user-role */

    @ApiOperation(value = "查询所有用户角色")
    @GetMapping("userRole/get/list/all")
    public ResultObject getAllAccessUserRole() {
        List<AccessUserRole> list = accessUserRoleService.list(null);
        if (list == null || list.isEmpty()){
            return ResultObject.error().message(ResultMessage.NO_RESULT);
        } else {
            return ResultObject.ok().data("items", list);
        }
    }

    @ApiOperation(value = "根据userId查询用户角色列表")
    @GetMapping("userRole/get/list/user/{userId}")
    public ResultObject getAccessUserRoleByUserId(
            @PathVariable String userId) {
        QueryWrapper<AccessUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<AccessUserRole> list = accessUserRoleService.list(wrapper);
        if (list == null || list.isEmpty()){
            return ResultObject.error().message(ResultMessage.NO_RESULT);
        } else {
            return ResultObject.ok().putList(list, list.size());
        }
    }

//    @ApiOperation(value = "根据roleId查询所有角色权限")
//    @GetMapping("userRole/get/list/{roleId}")
//    public ResultObject getAccessUserRoleByRoleId(
//            @PathVariable String roleId) {
//        QueryWrapper<AccessUserRole> wrapper = new QueryWrapper<>();
//        wrapper.eq("role_id", roleId);
//        List<AccessUserRole> list = accessUserRoleService.list(wrapper);
//        if (list == null || list.isEmpty()){
//            return ResultObject.error().message(ResultMessage.NO_RESULT);
//        } else {
//            return ResultObject.ok().data("items", list);
//        }
//    }

//    @ApiOperation(value = "删除角色权限")
//    @PostMapping("userRole/delete")
//    public ResultObject deleteAccessUserRole(
//            @RequestBody AccessUserRole accessUserRole) {
//        QueryWrapper<AccessUserRole> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_id", accessUserRole.getUserId())
//                .eq("role_id", accessUserRole.getRoleId());
//        if (accessUserRoleService.getOne(wrapper) == null){
//            return ResultObject.error().message(ResultMessage.NO_SUCH_OBJECT);
//        } else {
//            if (accessUserRoleService.remove(wrapper)) {
//                return ResultObject.ok().data("data", accessUserRole);
//            } else {
//                return ResultObject.error().message(ResultMessage.OBJECT_EXISTS_BUT_FAILED_TO_DELETE);
//            }
//        }
//    }

    @ApiOperation(value = "为用户设置角色，一个用户只能有一个角色")
    @PostMapping("userRole/set")
    public ResultObject insertAccessUserRole (
            @ApiParam("{userId: '', roleId: ''}")
            @RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String userId = jsonObject.getString("userId");
        String roleId = jsonObject.getString("roleId");
        if ("1000000000000000000".equals(userId))
            return ResultObject.error().message("Root管理员权限不允许更改");
        QueryWrapper<AccessUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        if (!accessUserRoleService.remove(wrapper)) { // 删除失败 可能是没有记录
            if (accessUserRoleService.getOne(wrapper) != null) { // 存在记录
                return ResultObject.error().message("设置失败");
            }
        }
        if (accessUserRoleService.save(new AccessUserRole().setUserId(userId).setRoleId(roleId))) {
            return ResultObject.ok();
        } else {
            return ResultObject.error().message("设置失败");
        }
    }

//    @GetMapping("permission/get/list/{userId}")
//    public ResultObject getPermissionValueListByUserId(
//            @PathVariable String userId) {
//        List<String> permissionValueList =
//                accessPermissionService.selectPermissionValueListByUserId(userId);
//        if (permissionValueList == null || permissionValueList.isEmpty()) {
//            return ResultObject.error();
//        } else {
//            return ResultObject.ok().data("items", permissionValueList);
//        }
//    }

//    @GetMapping("role/get/list/{userId}")
//    public ResultObject getRoleListByUserId(
//            @PathVariable String userId) {
//        List<AccessRole> roleList = accessUserRoleService.getRoleListByUserId(userId);
//        if (roleList == null) {
//            return null;
//        } else {
//            return ResultObject.ok().data("items", roleList);
//        }
//    }
}

